package cn.sc.summer.mybatis.builder;

import cn.hutool.core.util.ObjectUtil;
import cn.sc.summer.constant.enums.StatusEnum;
import cn.sc.summer.exception.hodler.SpringContextHolder;
import cn.sc.summer.exception.util.ip.IPUtil;
import cn.sc.summer.mybatis.po.Sql;
import cn.sc.summer.mybatis.util.MPUserUtil;
import cn.sc.summer.token.po.UserDetailX;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 类名：构造者实现类
 *
 * @author a-xin
 * @date 2023/9/5 14:47
 */
@Slf4j
public class SqlInfoBuilder extends SqlBuilder {

    private final Sql sql = new Sql();

    /**
     * 构造log发布的基础信息
     */
    @Override
    protected void buildLogInfo() {

        HttpServletRequest request = SpringContextHolder.getHttpServletRequest();
        if (ObjectUtil.isNotNull(request)) {
            sql.setReqUri(request.getRequestURI());
            sql.setReqIp(IPUtil.getIpAddr(request));
            sql.setReqUri(request.getRequestURI());
        }

        sql.setId(IdWorker.getIdStr());
        sql.setCreateTime(new Date());
        sql.setUpdateTime(new Date());
        sql.setDel(StatusEnum.ENABLE_OR_NOT_DELETED.getType());

        UserDetailX loginUser = MPUserUtil.getLoginUser();
        if (ObjectUtil.isNotNull(loginUser)) {
            sql.setCreateUser(loginUser.getUserId());
            sql.setUpdateUser(loginUser.getUserId());
            sql.setDataTenantId(loginUser.getTenantId());
        }
    }

    @Override
    protected Sql build() {
        return sql;
    }

}
